import { pageReleaseReceipt, releaseTreeReceiptAssignContact } from '@/services/api/api-needs';
import { UserOutlined } from '@ant-design/icons';
import { ActionType, DrawerForm, ProFormInstance, ProList } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Avatar, Col, Row, Space, Spin, Tag, Typography } from 'antd';
import Tree, { DataNode } from 'antd/es/tree';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';

interface ReceiptNeedsProps {
  interviewId: string;
  onRefurbish: () => void;
}

const ReceiptNeeds: React.FC<ReceiptNeedsProps> = ({ interviewId, onRefurbish }) => {
  const access = useAccess();
  const { initialState, setInitialState } = useModel('@@initialState');

  const [loading, setLoading] = useState(false);

  const formRef = useRef<ProFormInstance>();

  const actionRef = useRef<ActionType>();

  const [openAddActive, setOpenAddActive] = useState<boolean>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  const [dataTreeAddress, setDataTreeAddressState] = useState<DataNode[]>();

  const [viewCombineIds, setViewCombineIdsState] = useState<string[]>([]);

  /**
   * 加载组织树请求网络
   */
  const loadAddressTreeData = async () => {
    try {
      setLoading(true);

      const response = await releaseTreeReceiptAssignContact({
        id: interviewId,
      });

      console.log(readyTreeAddressData(response.data));

      if (response.code === 0) {
        setDataTreeAddressState(readyTreeAddressData(response.data));
      }

      setLoading(false);
    } catch (error) {}
  };

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeAddressData(data: Array<UserData.Organization>): any {
    const treeData = new Array();
    console.log(data);

    if (data) {
      data.forEach((val, idx, array) => {
        if (val.isCombine == 1 && val.isView == 1) {
          setViewCombineIdsState([...viewCombineIds, val.id]);
        }
        treeData.push({
          title: (
            <>
              <span>{val.name}</span>
              {val?.isCombine == 1 &&
                val?.isView == 1 &&
                (val?.isReply == 1 ? (
                  <Tag bordered={false} color="green">
                    已回复
                  </Tag>
                ) : (
                  <Tag bordered={false} color="orange">
                    未回复
                  </Tag>
                ))}
              {val?.marks && val?.marks.length > 0 && (
                <>
                  <Space wrap>
                    {val?.marks.map((item) => (
                      <Tag bordered={false} color="orange">
                        {item}
                      </Tag>
                    ))}
                  </Space>
                </>
              )}
            </>
          ),
          key: val.id,
          isCombine: val.isCombine,
          children: readyTreeAddressData(val.children as Array<UserData.Organization>),
        });
      });
    }
    return treeData;
  }

  return (
    <DrawerForm
      key="drawer_form_add_release"
      title="阅读和回复"
      drawerProps={{
        destroyOnClose: true,
        width: 900,
        maskClosable: false,
      }}
      formRef={formRef}
      trigger={<a>点击查看详情</a>}
      initialValues={{
        initiateOrganization: initialState?.currentUser?.organizationName,
      }}
      open={openAddActive}
      onOpenChange={(visible) => {
        if (visible) {
          loadAddressTreeData();
        } else {
          setViewCombineIdsState([]);
        }
        setOpenAddActive(visible);
      }}
      layout="horizontal"
      submitter={false}
    >
      <Spin spinning={loading}>
        <Row>
          <Col span={10}>
            {dataTreeAddress && (
              <Tree
                style={{
                  marginTop: '16px',
                }}
                checkedKeys={viewCombineIds}
                treeData={dataTreeAddress}
                defaultExpandAll
                checkable={true}
                selectable={false}
              />
            )}
          </Col>
          <Col span={14}>
            <ProList<NeedsData.Receipt>
              style={{
                marginTop: 10,
              }}
              ghost
              request={async (params = {}) => {
                const response = await pageReleaseReceipt({ ...params, id: interviewId, type: 2 });
                return Promise.resolve({
                  data: response.data.data,
                  total: response.data.total,
                  success: response.code === 0,
                });
              }}
              actionRef={actionRef}
              rowKey="id"
              dateFormatter="string"
              bordered
              search={false}
              sticky
              pagination={{
                showQuickJumper: true,
                showSizeChanger: true,
                defaultPageSize: 20,
              }}
              metas={{
                title: {
                  dataIndex: 'createdOrganizationName',
                  render: (dom, entity) => {
                    return (
                      <Space size={0}>
                        <Tag color={entity.type === 2 ? '#87d068' : '#1AA15F'}>
                          {entity.type === 2 ? '已回复' : '已阅读'}
                        </Tag>
                        <Avatar
                          size="small"
                          icon={<UserOutlined />}
                          src={entity.createdOrganizationAvatar}
                        />
                        <span
                          style={{
                            marginLeft: '5px',
                            marginRight: '5px',
                          }}
                        >
                          {entity.createdOrganizationName}
                        </span>
                        -
                        <span
                          style={{
                            marginLeft: '5px',
                          }}
                        >
                          {entity.createdAccountName}
                        </span>
                        {/* {currentUser?.id === entity.createdAccountId && (
                      <UpdateReceipt
                        item={entity}
                        onSave={() => {
                          actionRef.current?.reload();
                        }}
                      />
                    )} */}
                      </Space>
                    );
                  },
                },
                description: {
                  dataIndex: 'content',
                  render: (dom, entity) => {
                    return entity.content ? (
                      <div style={{ display: 'flex', alignItems: 'flex-start' }}>
                        <div style={{ width: 65, whiteSpace: 'nowrap' }}>回复内容：</div>
                        <Typography.Paragraph
                          style={{ flexGrow: 1, margin: 0 }}
                          type="secondary"
                          ellipsis={{
                            rows: 2,
                            expandable: true,
                            onEllipsis: (ellipsis) => {
                              console.log('Ellipsis changed:', ellipsis);
                            },
                          }}
                          copyable
                        >
                          {entity.content}
                        </Typography.Paragraph>
                      </div>
                    ) : (
                      <></>
                    );
                  },
                },
                actions: {
                  render(dom, entity, index, action, schema) {
                    return <a>{entity.createdTime}</a>;
                  },
                },
              }}
              toolbar={{}}
              toolBarRender={false}
            />
          </Col>
        </Row>
      </Spin>
    </DrawerForm>
  );
};
export default ReceiptNeeds;
